<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Wechat;
use app\models\RedisStore;

class WechatController extends Controller
{
    public $enableCsrfValidation = false;

    protected $app_id = WECHAT_APPID;
    protected $app_secret = WECHAT_APPSECRET;
    protected $token = WECHAT_TOKEN;
    protected $encoding_key = WECHAT_ENCODINGAESKEY;

    public function beforeAction($action)
    {
        //记录日志到专用文件中
        Yii::$app->tool->setLogFile('wechat');
        return parent::beforeAction($action);
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    protected function getOptions()
    {
        return array(
            'token'=> $this->token,
            'encodingaeskey'=> $this->encoding_key,
            'appid'=> $this->app_id,
            'appsecret'=>$this->app_secret,
        );
    }

    public function actionIndex()
    {
        $options = [
            'token' => $this->token,
        ];

        $weObj = new Wechat($options);
        $weObj->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
        $type = $weObj->getRev()->getRevType();
        $open_id = $weObj->getRevFrom();
        $event_arr = $weObj->getRevEvent();
        $event_key = isset($event_arr['key']) ? $event_arr['key'] : '';
        $event_type = $event_arr['event'];

        //Yii::error('wechat:' . json_encode($event_arr) . ' eventtype:' . $event_type);

        switch($type) {
            case Wechat::MSGTYPE_TEXT:
                $weObj->text("您好，您的反馈已收到，我们将尽快回复您:)")->reply();
                exit;
                break;
            case Wechat::MSGTYPE_EVENT:
                if ($event_key == 'verifycode') {
                    $weObj->text("请关注“天天钱庄VIP”微信公众号，完成微信绑定")->reply();//旧微信号关闭，20170220
                    // $bind_msg = $this->bindWechat($open_id);
                    // $weObj->text($bind_msg)->reply();

                } elseif ($event_key == 'account') {
                    $weObj->text("请关注“天天钱庄VIP”微信公众号，完成微信绑定")->reply();//旧微信号关闭，20170220
                    // $weObj->text($this->queryAccount($open_id))->reply();

                } elseif ($event_key == 'about') {
                    $weObj->text('天天钱庄是一款用手机赚钱的强大应用，零投入无须任何本金，提现方便快捷，了解更多请回到天天钱庄官网（回到手机Safari浏览器或打开天天钱庄App）')->reply();

                } elseif ($event_type == Wechat::EVENT_SUBSCRIBE) {
                    //$this->sendWelcomeMsg($open_id);
                    $weObj->text('终于等到你，还好没放弃 :)')->reply();
                }

                break;
            case Wechat::MSGTYPE_IMAGE:
                break;
            default:
                $weObj->text("您好，您的反馈已收到，钱庄小二将尽快回复您:)")->reply();
        }
        exit;
    }

    public function bindInvite($open_id, $from_user)
    {
        $from_user_id = str_replace('qrscene_', '', $from_user);

        $redis = new RedisStore();
        return $redis->setInviteOpenid($open_id, $from_user_id);
    }

    public function sendWelcomeMsg($open_id)
    {
        $weObj = new Wechat($this->getOptions());

        $data = [
            'touser' => $open_id,
            'msgtype' => 'news',
            'news' => [
                "articles" => [
                    [
                        'title' => '终于等到你，还好没放弃',
                        //'title' => '点击“开始赚钱”，开启掌上赚钱之旅',
                        //'description' => '下载天天钱庄送1元红包，下载应用领1-4元，比某宝收益强多了！',
                        'description' => '点击开始试玩，Get最新最酷的果粉技巧',
                        //'url' => 'https://appems.com/install',
                        'url' => APP_ANCCLOUD_HOST_PATH . '/install',
                        //'picurl' => 'https://appems.com/img/wechat_msg_head.jpg',
                        'picurl' => 'http://7xrk3a.com1.z0.glb.clouddn.com/welcome.jpg',
                    ]
                ],
            ],
        ];

        return $weObj->sendCustomMessage($data);
    }

    public function actionDebug()
    {
        /**
        $data = [
            'touser' => 'oEld1v2an6_HOJFkvo7k1IKDfTyo',
            'msgtype' => 'mpnews',
            'mpnews' => [
                "media_id" => "402735065",
            ],
        ];
         * **/

        $data = [
            'touser' => 'oEld1v2an6_HOJFkvo7k1IKDfTyo',
            'msgtype' => 'news',
            'news' => [
                "articles" => [
                    [
                        'title' => '终于等到你，还好没放弃',
                        'description' => '下载天天钱庄送1元红包，下载应用领1-4元，比某宝收益强多了！',
                        'url' => HOST_PATH.'/install',
                        'picurl' => HOST_PATH.'/img/wechat_install.jpg',
                    ]
                ],
            ],
        ];
        print_r(json_encode($data));exit;

        $weObj = new Wechat($this->getOptions());

        $callback = 'https://api.appems.com/test.html';
        $getOauthRedirect = $weObj->getOauthRedirect($callback, 'STATE', 'snsapi_userinfo');

        print_r($getOauthRedirect);
    }


    public function actionSyncmenu()
    {
        $options = [
            'token' => $this->token,
        ];

        $data = [
            'button' => [
                ['type' => 'click', 'name' => '绑定账号', 'key' => 'verifycode'],
                ['type' => 'click', 'name' => '关于我们', 'key' => 'about'],
            ]
        ];

        $token_api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->app_id . "&secret=" . $this->app_secret;
        echo $token_api . PHP_EOL;

        echo json_encode($data);exit;

        $weObj = new Wechat($options);
        $weObj->checkAuth($this->app_id, $this->app_secret, $this->token);

        var_dump($weObj->createMenu($data));
        var_dump($weObj->errCode);


        exit;
    }

    private function queryAccount($open_id)
    {
        $userInfo = UserInfo::findOne(['open_id' => $open_id]);

        if ( empty($userInfo) ) {
            return '请点击“开始赚钱”后进入钱庄下载钱庄App，进行自动账户注册';
        }

        $msg = 'ID: ' . $userInfo->user_id . '                           ';
        $msg .= '余额: ' . Yii::$app->tool->moneyFormat($userInfo->balance) . '                            ';
        $msg .= '总收入: ' . Yii::$app->tool->moneyFormat($userInfo->total_income);

        return $msg;
    }

    private function bindWechat($open_id)
    {
        $userInfo = UserInfo::findOne(['open_id' => $open_id]);

        if ($userInfo) {
            $msg = 'ID: ' . $userInfo->user_id . '                           ';
            $msg .= '余额: ' . Yii::$app->tool->moneyFormat($userInfo->balance) . '                            ';
            $msg .= '总收入: ' . Yii::$app->tool->moneyFormat($userInfo->total_income);

            return $msg;
        }

        $verify_code = $this->getVerifyCode($open_id);
        Yii::warning("bind_wechat, open_id:$open_id, code:$verify_code");
        return '您的微信验证码为: ' . $verify_code . '，请返回天天钱庄网页输入（有效时间三分钟）。';
    }

    /**
     *
     */
    private function getVerifyCode($open_id)
    {
        $verifycode = mt_rand(101010, 999999);

        Yii::$app->rCache->set(REDIS_WECHAT_CODE_PREFIX . $verifycode, $open_id, REDIS_WECHAT_CODE_EXPIRE);

        return $verifycode;
    }

    private function _checkSignature()
    {
        $signature = Yii::$app->request->get('signature');
        $timestamp = Yii::$app->request->get('timestamp');
        $nonce = Yii::$app->request->get('nonce');

        $tmpArr = array($this->token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ) {
            return true;
        } else{
            return false;
        }
    }

    public function actionRedirect()
    {
        return $this->render('redirect');
    }
}
